const bcrypt = require('bcryptjs');

const errcode = require(__util + "/errcode")

const models = require(__base + "/models");

module.exports = async (req, res, next) => {
  const { username } = req.account
  const { oldPassword, newPassword } = req.body
  console.log(req.body)

  if (!oldPassword) {
    return res.json(errcode.PASSWORD_EMPTY)
  }
  if (!newPassword) {
    return res.json(errcode.NEW_PASSWORD_EMPTY)
  }
  if (oldPassword === newPassword) {
    return res.json(errcode.SAME_PASSWORD)
  }

  const checkRet = await checkAccount(username, oldPassword)
  if (checkRet.errcode) {
    return res.json(checkRet)
  } else {
    await updatePassword(username, newPassword)
    return res.json(
      errcode.SUCCESS()
    );
  }
};

// 更新密码
const updatePassword = async (username, newPassword) => {
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(newPassword, salt);

  return await models.Account.update({
    hash: hash
  }, {
    where: {
      username: username
    }
  })
}

// 检查数据库用户账号密码是否正确
const checkAccount = async (username, oldPassword) => {
  const accountInfo = await models.Account.findOne({
    where: {
      username: username
    }
  })
  if (accountInfo) {
    const checkPwdRet = await bcrypt.compareSync(oldPassword, `${accountInfo.hash}`)
    if (checkPwdRet) {
      return errcode.SUCCESS()
    } else {
      return errcode.PASSWORD_INVALID
    }
  } else {
    return errcode.USERNAME_NOT_EXIST
  }
}